package dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import entity.Document;
import util.DBHelp;
import util.RowMapper;

public class DocumentDao {

	private DBHelp<Document> db=new DBHelp<Document>();
	
	public void save(Document doc){
		String sql="insert into t_document (id,title,content,createtime,user_id,project_id) values(?,?,?,?,?,?)";
		db.executeSQL(sql, doc.getId(),doc.getTitle(),doc.getContent(),doc.getCreatetime(),doc.getUser_id(),doc.getProject_id());
	}
	
	public Document findDocumentById(String id){
		String sql="select id,title,content,createtime,user_id,project_id from t_document where id=? ";
		return db.executeQueryToObject(sql,new DocumentRowMapper(),id);
	}
	
	
	public List<Document> findDocumentAll(String pid){
		String sql="select t_document.id,title,content,createtime,user_id,project_id, username from t_document LEFT JOIN t_user ON t_document.user_id=t_user.id where project_id=? order by createtime desc";
		return db.executeQueryToList(sql, new RowMapper<Document>(){

			public Document mapRow(ResultSet rs) throws SQLException {
				Document d=new Document();
				
				d.setId(rs.getString("id"));
				d.setContent(rs.getString("content"));
				d.setCreatetime(rs.getString("createtime"));
				d.setProject_id(rs.getString("project_id"));
				d.setTitle(rs.getString("title"));
				d.setUser_id(rs.getString("user_id"));
				d.setUsername(rs.getString("username"));
				return d;
			}},pid);
	}
	
	public class DocumentRowMapper implements RowMapper<Document>{

		public Document mapRow(ResultSet rs) throws SQLException {
			
			Document d=new Document();
			
			d.setId(rs.getString("id"));
			d.setContent(rs.getString("content"));
			d.setCreatetime(rs.getString("createtime"));
			d.setProject_id(rs.getString("project_id"));
			d.setTitle(rs.getString("title"));
			d.setUser_id(rs.getString("user_id"));
			
			return d;
			
		}
		
	}

	public void update(Document dt) {
		String sql="update t_document set title=?,content=? where id=?";
		db.executeSQL(sql,dt.getTitle(),dt.getContent(),dt.getId());
		
	}
	
	public void del(String id){
		String sql="delete from t_document where id=?";
		db.executeSQL(sql,id);
	}
}

